/*
 * @Author: xiaosihan 
 * @Date: 2024-04-12 10:00:00 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2025-10-Tu 02:46:06
 */
import { Button, message, Modal } from "antd";
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts';
import { useState } from "react";
import tinypngApi from "@api/tinypngApi";
import { ApiResponseTestData } from "@type";
import axios from "axios";
import styles from './index.module.less';

interface ApiResponseTestProps {
    // 可以根据需要添加props
}

const ApiResponseTest: React.FC<ApiResponseTestProps> = (props) => {
    // 接口响应测试相关状态
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [apiTestData, setApiTestData] = useState<ApiResponseTestData[]>([]);
    const [isTesting, setIsTesting] = useState(false);
    const [testProgress, setTestProgress] = useState(0);
    const [nextRequestCountdown, setNextRequestCountdown] = useState<number | null>(null);
    const [currentInterval, setCurrentInterval] = useState<number | null>(null);

    // 获取接口响应测试数据
    const getApiResponseTestData = async () => {
        try {
            const data = await tinypngApi.get_api_response_test();
            setApiTestData((data as unknown as ApiResponseTestData[]) || []);
        } catch (error) {
            message.error('获取接口响应测试数据失败');
            console.error(error);
        }
    };

    // 生成图表配置
    const getChartOption = () => {
        // 准备数据
        const sortedData = [...apiTestData].sort((a, b) => a.interval_time - b.interval_time);
        const xAxisData = sortedData.map(item => item.interval_time);
        const yAxisData = sortedData.map(item => item.response_time);

        // 格式化x轴标签
        const formatXAxisLabel = (value: number) => {
            const minutes = Math.floor(value / 60);
            const seconds = value % 60;

            if (minutes === 0) {
                return `${seconds}秒`;
            } else if (seconds === 0) {
                return `${minutes}分`;
            } else {
                return `${minutes}分${seconds}秒`;
            }
        };

        return {
            title: {
                text: '接口响应时间测试',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                formatter: (params: any) => {
                    const dataIndex = params[0].dataIndex;
                    const item = sortedData[dataIndex];
                    const formattedInterval = formatXAxisLabel(item.interval_time);
                    return `间隔时间: ${formattedInterval}<br/>响应时间: ${item.response_time.toFixed(2)}ms`;
                }
            },
            xAxis: {
                type: 'category',
                data: xAxisData,
                name: '间隔时间',
                nameLocation: 'middle',
                nameGap: 30,
                axisLabel: {
                    formatter: formatXAxisLabel,
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value',
                name: '响应时间 (ms)',
                nameLocation: 'middle',
                nameGap: 40
            },
            grid: {
                left: '3%',
                right: '3%',
                bottom: '3%',
                top: '3%',
                containLabel: true
            },
            series: [
                {
                    name: '响应时间',
                    type: 'line',
                    data: yAxisData,
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 6,
                    lineStyle: {
                        width: 2,
                        color: '#1890ff'
                    },
                    itemStyle: {
                        color: '#1890ff'
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {
                                offset: 0,
                                color: 'rgba(24, 144, 255, 0.3)'
                            },
                            {
                                offset: 1,
                                color: 'rgba(24, 144, 255, 0.1)'
                            }
                        ])
                    }
                }
            ]
        };
    };

    // 打开接口响应测试弹窗
    const showApiResponseTestModal = async () => {
        setIsTesting(false);
        setTestProgress(0);
        setIsModalVisible(true);
        await getApiResponseTestData();
    };

    // 关闭弹窗
    const handleModalCancel = () => {
        setIsModalVisible(false);
    };

    // 执行接口响应测试
    const runApiResponseTest = async () => {
        if (isTesting) return;

        setIsTesting(true);
        setTestProgress(0);

        // 发送请求
        await tinypngApi.ping();

        // 间隔时间列表（1,2,4,8,16,32,60,120,180,240,300,360,420秒）
        // const intervals = [1, 2, 4, 8, 16, 32, 60, 120, 180, 240, 300, 360, 420];
        // const intervals = [361, 362, 363, 364, 365, 366, 367, 368, 369, 421, 422, 423, 424, 425, 426, 427, 428, 429];

        const intervals = new Array(6 * 5).fill(0).map((_, index) => index * 10);
        intervals.push(...new Array(55).fill(0).map((_, index) => (index + 6) * 60));

        for (let i = 0; i < intervals.length; i++) {
            const interval = intervals[i];
            // 设置当前间隔时间
            setCurrentInterval(interval);

            try {
                // 如果不是第一个间隔，则先等待指定时间并显示倒计时
                if (i > 0) {
                    // 设置初始倒计时为间隔时间
                    setNextRequestCountdown(interval);

                    // 使用setInterval实现倒计时
                    await new Promise(resolve => {
                        const countdownInterval = setInterval(() => {
                            setNextRequestCountdown(prev => {
                                if (prev !== null && prev > 1) {
                                    return prev - 1;
                                } else {
                                    clearInterval(countdownInterval);
                                    setNextRequestCountdown(null);
                                    resolve(null);
                                    return null;
                                }
                            });
                        }, 1000);
                    });
                }

                // 记录请求开始时间
                const startTime = Date.now();

                // 发送请求
                await tinypngApi.ping();

                // 计算响应时间
                const responseTime = Date.now() - startTime;

                // 保存测试结果
                await tinypngApi.save_api_response_test(interval, responseTime);

                // 更新本地数据
                await getApiResponseTestData();

                // 更新进度
                setTestProgress(Math.round(((i + 1) / intervals.length) * 100));
            } catch (error) {
                console.error(`间隔${interval}秒测试失败:`, error);
                message.error(`间隔${interval}秒测试失败`);
            }
        }

        setIsTesting(false);
        setNextRequestCountdown(null);
        setCurrentInterval(null);
        message.success('接口响应测试完成');
    };

    // 清空所有接口响应测试数据
    const clearApiResponseTestData = async () => {
        Modal.confirm({
            title: '确认清空',
            content: '确定要清空所有接口响应测试数据吗？此操作不可恢复。',
            onOk: async () => {
                try {
                    await tinypngApi.clear_api_response_test();
                    setApiTestData([]);
                    message.success('数据已清空');
                } catch (error) {
                    message.error('清空数据失败');
                    console.error(error);
                }
            }
        });
    };
    // 图表组件替代了表格，此处不再需要表格列定义

    return (
        <>
            {/* 触发按钮 */}
            <Button
                loading={isTesting}
                size="small"
                type="primary"
                onClick={showApiResponseTestModal}
            >接口响应测试</Button>

            {/* 接口响应测试弹窗 */}
            <Modal
                title={
                    <>
                        接口响应测试
                        {isTesting && currentInterval !== null && (
                            <span style={{ marginLeft: 10, color: '#1890ff' }}>
                                (本次间隔时间 {currentInterval} 秒{nextRequestCountdown !== null ? `, 距离下次请求还剩 ${nextRequestCountdown} 秒` : ''})
                            </span>
                        )}
                    </>
                }
                open={isModalVisible}
                onCancel={handleModalCancel}
                footer={[
                    <Button key="cancel" onClick={handleModalCancel}>
                        关闭
                    </Button>
                ]}
                width={700}
                maskClosable={false}
                centered
            >
                <div style={{ marginBottom: 16, display: 'flex', gap: 10 }}>
                    <Button
                        type="primary"
                        loading={isTesting}
                        onClick={runApiResponseTest}
                        disabled={isTesting}
                    >
                        {isTesting ? '测试中...' : '开始测试'}
                    </Button>
                    {isTesting && (
                        <span style={{ marginLeft: 16 }}>进度: {testProgress}%</span>
                    )}
                    {!isTesting && apiTestData.length > 0 && (
                        <Button
                            type="default"
                            danger
                            onClick={clearApiResponseTestData}
                        >
                            清空所有数据
                        </Button>
                    )}
                </div>
                <div style={{ height: '400px', width: '700px' }}>
                    <ReactECharts
                        option={getChartOption()}
                        style={{ height: '400px', width: '700px' }}
                        opts={{ renderer: 'canvas' }}
                    />
                </div>
            </Modal>
        </>
    );
};

export default ApiResponseTest;